package top.market.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yungouos.pay.util.PaySignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.market.config.AliPayConfig;
import top.market.config.WxPayConfig;
import top.market.model.entity.OrderStatusEnum;
import top.market.model.entity.Orders;
import top.market.service.IOrdersService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Description:
 * @Author: liyuhai
 * @Date: 2025/4/4
 */
@RestController
@RequestMapping("/pay")
public class PayNotifyController {

    @Autowired
    private IOrdersService ordersService;

    // 微信支付回调地址，这里用到 第三方工具yungouos
    @RequestMapping("/notify/paySuccess")
    public String notify(@RequestParam Map<String, String> data, HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("接受到支付结果回调");
            System.out.println(data.toString());
            String payChannel = data.get("payChannel");
            String attach = data.get("attach");
            if (StrUtil.isBlank(payChannel)) {return "payChannel is not null"; }
            String key = null;
            if ("wxpay".equals(payChannel)) {
                key = WxPayConfig.key;
            }
            if ("alipay".equals(payChannel)) {
                key = AliPayConfig.key;
            }
            boolean sign = PaySignUtil.checkNotifySign(request, key);
            System.out.println("签名验证：" + sign);
            if (!sign) {
                return "sign fail";
            }
            String outTradeNo = data.get("outTradeNo"); // 商户平台订单号
            String payNo = data.get("payNo"); //
            String time = data.get("time");
            String code = data.get("code");
            if (Integer.valueOf(code).intValue() != 1) { return "pay fail"; }
            // 这里支付成功后，将数据库表的数据进行更新, 支付状态设置为已支付, 这里的产生订单号的方式是 系统时间
            // 保存支付状态信息， orders.setNumber(String.valueOf(System.currentTimeMillis()));
            LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Orders::getPayStatus, OrderStatusEnum.PENDING_CONFIRMATION);
            updateWrapper.eq(Orders::getNumber, outTradeNo);
            boolean success = ordersService.update(updateWrapper);
            if (!success) { return "fail"; }
            PrintWriter out = response.getWriter();
            out.print("SUCCESS");
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
